<template>
  <div>
    <el-dialog :title="ruleForm.id == '' ? '添加维修申请' : '编辑维修申请'" :visible.sync="addEditIsDialog_c"
      @close="resetForm('formName')" width="800px">
      <el-form :model="ruleForm" :rules="rules" ref="formName" label-width="120px" class="demo-ruleForm"
        :class="{ 'form-rules-show': seeType }">
        <el-row>
          <el-col :span="24">
            <el-form-item label="公司名称：" prop="companyId">
              <el-cascader v-model="ruleForm.companyId" placeholder="请选择公司名称" :options="companyArray" :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
                children: 'childList',
              }" @change="changeTreeItem" clearable :disabled="seeType"></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="基地名称：" prop="baseId">
              <el-select v-model="ruleForm.baseId" placeholder="请选择基地名称" @change="baseChange" clearable>
                <el-option v-for="item in baseArray" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="鱼池名称：" prop="fishpondId">
              <el-select v-model="ruleForm.fishpondId" placeholder="请选择鱼池名称" clearable>
                <el-option v-for="item in fishpondArray" :key="item.id" :label="item.name"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障内容：" prop="content">
              <el-input v-model="ruleForm.content" placeholder="请输入故障内容" clearable maxlength="400" type="textarea"
                :rows="2" show-word-limit :disabled="seeType"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="故障图片：" prop="faultImagesArr">
              <MultipleImgUpload sirProps="image" :sirUrl="ruleForm.faultImagesArr" :limit="4" @upSuccess="upSuccess"
                :disabled="seeType"></MultipleImgUpload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="维修清单：" prop="repairList">
              <template>
                <el-table :data="ruleForm.repairList" @row-dblclick="dbclick" border style="width: 100%"
                  :header-cell-style="tabHeadStyle" :cell-style="tabcellStyle" :row-style="rowStyle"
                  :cell-class-name="tableCellClassName">
                  <el-table-column prop="goods" label="物品" align="center">
                    <template slot-scope="scope">
                      <!--v-if去判断双击的是不是当前单元格-->
                      <el-input @blur="hideInput" size="mini" :ref="scope.row.index + ',' + scope.column.index"
                        v-model="scope.row.goods" v-if="scope.row.index + ',' + scope.column.index == currentCell">
                      </el-input>
                      <span v-else>{{ scope.row.goods }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="单价（元）" align="center">
                    <template slot-scope="scope">
                      <el-input @blur="hideInput" size="mini" :ref="scope.row.index + ',' + scope.column.index"
                        v-model="scope.row.price" v-if="scope.row.index + ',' + scope.column.index == currentCell">
                      </el-input>
                      <span v-else>{{ scope.row.price }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="num" label="数量" align="center">
                    <template slot-scope="scope">
                      <el-input @blur="hideInput" size="mini" :ref="scope.row.index + ',' + scope.column.index"
                        v-model="scope.row.num" v-if="scope.row.index + ',' + scope.column.index == currentCell">
                      </el-input>
                      <span v-else>{{ scope.row.num }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <span class="nx-btn nx-edit" @click="add">添加物品</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批人：" prop="approvalId">
              <el-select v-model="ruleForm.approvalId" placeholder="请选择审批人" clearable>
                <el-option v-for="item in approvalArray" :key="item.id" :label="item.realName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('formName')">取 消</el-button>
        <el-button class="btn-light-blue" @click="submitForm('formName')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
import MultipleImgUpload from "@/components/MultipleImgUpload.vue";
import { getDataRepair, saveDataTaskInspect } from "@/api/repair";
import { getObjFishponds } from "@/api/fishpond";
import { getCompanyInfoTree } from "@/api/company";
import { getSysCompanyBases, getSysUsers } from "@/api/system";

export default {
  components: {
    MultipleImgUpload
  },
  props: {
    addEditId: {
      type: String,
      default: "",
    },
    addEditStatus: {
      type: String,
      default: "add",
    },
    addEditIsDialog: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // 表头样式
      tabHeadStyle: {
        "background-color": "#FAFAFA",
        color: "#333333",
        "font-weight": "bold",
        "text-align": "center",
      },
      // 行样式
      tabcellStyle: {
        color: "#666",
      },
      rowStyle: {
        height: "40px",
      },
      ruleForm: {
        // 表单字段
        id: "",
        companyId: "",
        baseId: "",
        fishpondId: "",
        approvalId: "",
        content: "",
        faultImages: "",
        faultImagesArr: [],
        repairListJosn: "",
        repairList: [],
      },
      rules: {
        // 表单规则
        companyId: [
          { required: true, message: "请选择公司名称", trigger: "change" },
        ],
        baseId: [
          { required: true, message: "请选择基地名称", trigger: "change" },
        ],
        fishpondId: [{ required: true, message: "请选择鱼池名称", trigger: "change" }],
        approvalId: [{ required: true, message: "请选择审批人", trigger: "change" }],
        content: [{ required: true, message: "请输入故障内容", trigger: "blur" }],
        faultImagesArr: [{ required: true, message: "请上传故障图片", trigger: "change" }],
        repairList: [{ required: true, message: "请填入维修清单", trigger: "blur" }],
      },
      // 用一个字符串来保存当前双击的是哪一个单元格
      currentCell: null,
      addEditIsDialog_c: false, // 弹窗是否显示
      seeType: false, // 是否禁用
      baseArray: [], // 基地集合
      companyArray: [], // 公司集合
      fishpondArray: [], // 鱼池集合
      approvalArray: [], // 审批人集合
      userType: "", // 用户类型（0超级管理员，1公司管理员）
    };
  },
  watch: {
    addEditIsDialog(val) {
      this.addEditIsDialog_c = val;
      if (this.addEditIsDialog_c) {
        // 添加
        if (this.addEditStatus == "add") {
          this.ruleForm.id = "";
          this.seeType = false;
        }

        // 编辑
        if (this.addEditStatus == "edit") {
          this.ruleForm.id = this.addEditId;
          this.seeType = false;
          this.getDetail();
        }

        // 查看
        if (this.addEditStatus == "see") {
          this.ruleForm.id = this.addEditId;
          this.seeType = true;
          this.getDetail();
        }

        this.userType = Number(window.localStorage.getItem("userType"));

        // 获取公司列表
        this.getCompanyInfoTree();

        this.getSysCompanyBases();
      }
    },
  },
  methods: {
    // 详情
    getDetail() {
      getDataRepair({ id: this.addEditId }).then((res) => {
        if (res.code == 200) {
          res.data.faultImagesArr =
            res.data.faultImages != undefined ? res.data.faultImages.split(",") : [];
          res.data.repairList =
            res.data.repairListJosn != undefined ? JSON.parse(res.data.repairListJosn) : [];
          this.ruleForm = res.data;
           console.log(res.data.repairList);

          // 获取公司列表
          this.getCompanyInfoTree();

          this.getSysCompanyBases();

          this.getObjFishponds();

          // 获取审批人列表
          this.getSysUsers();
        }
      });
    },
    // 提交
    submitForm(formName) {
      this.ruleForm.faultImages = this.ruleForm.faultImagesArr.toString();
      this.ruleForm.repairListJosn = JSON.stringify(this.ruleForm.repairList);
      this.$refs[formName].validate((valid) => {
        if (valid) {
          saveDataTaskInspect(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.$message({
                type: "success",
                message: res.msg,
              });

              // 关闭弹窗
              this.$parent.closeAddEdit();
              // 刷新列表
              this.$parent.onSubmit();
            }
          });
        }
      });
    },
    // 取消
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.$parent.closeAddEdit();
    },
    // 获取公司列表
    getCompanyInfoTree() {
      if (this.ruleForm.userType === "") {
        return;
      }

      if (this.ruleForm.userType == 0) {
        // 超级管理员，公司只有一个总公司
        this.companyArray = [
          {
            id: 0,
            name: "总公司",
            parentId: 0,
          },
        ];
      } else {
        getCompanyInfoTree({}).then((res) => {
          if (res.code == 200) {
            this.companyArray = res.data;
          }
        });
      }
    },
    // 公司下拉切换
    changeTreeItem(val) {
      if (val) {
        this.ruleForm.companyId = val[val.length - 1];
      } else {
        this.ruleForm.companyId = "";
      }

      this.ruleForm.baseId = "";
      this.baseArray = [];

      this.ruleForm.approvalId = "";
      this.approvalArray = [];

      // 获取基地列表
      this.getSysCompanyBases();

      // 获取审批人列表
      this.getSysUsers();
    },
    // 获取基地列表
    getSysCompanyBases() {
      if (this.ruleForm.companyId === "" || this.ruleForm.companyId == null) {
        return;
      }

      getSysCompanyBases({ id: this.ruleForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.baseArray = res.data;
        }
      });
    },
    // 基地下拉切换
    baseChange() {
      this.ruleForm.fishpondId = "";
      this.fishpondArray = [];

      // 获取鱼池列表
      this.getObjFishponds();
    },
    // 获取鱼池列表
    getObjFishponds() {
      if (
        this.ruleForm.baseId === "" ||
        this.ruleForm.baseId == null
      ) {
        return;
      }

      getObjFishponds({ baseId: this.ruleForm.baseId, companyId: this.ruleForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.fishpondArray = res.data;
        }
      });
    },
    // 获取审批人列表
    getSysUsers() {
      if (this.ruleForm.companyId === "" || this.ruleForm.companyId == null) {
        return;
      }
      getSysUsers({ id: this.ruleForm.companyId }).then((res) => {
        if (res.code == 200) {
          this.approvalArray = res.data;
        }
      });
    },
    //添加
    add() {
      if (this.ruleForm.repairList != null) {
        this.ruleForm.repairList.push({
          goods: "",
          price: "",
          num: "",
        });
      } else {
        return;
      }
    },
    // 上传图片
    upSuccess(data) {
      this.ruleForm.faultImagesArr = data;
    },

    // 给单元格绑定横向和竖向的index，这样就能确定是哪一个单元格
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      row.index = rowIndex;
      column.index = columnIndex;
    },
    // 获得当前双击的单元格的横竖index，然后拼接成一个唯一字符串用于判断，并赋给currentCell
    // 拼接后类似这样："1,0","1,1",
    dbclick(row, column) {
      this.currentCell = row.index + ',' + column.index;
      // 这里必须要setTimeout，因为在点击的时候，input才刚被v-if显示出来，不然拿不到dom
      setTimeout(() => {
        // 双击后自动获得焦点
        this.$refs[row.index + ',' + column.index].focus();
      })
    },
    // 当input失去焦点的时候，隐藏input
    hideInput() {
      this.currentCell = null;
    }
  },
};
</script>

<style lang="less" scoped>
.demo-ruleForm {
  width: 95%;
  margin: 0 auto;
  padding-top: 10px;
}

.el-cascader {
  width: 100%;
}

.el-select {
  width: 100%;
}
</style>
